package cool.tianyou.blue.bird.config;

import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.TimedCache;
import cool.tianyou.blue.bird.common.model.entity.QrcodeLoginInfo;
import cool.tianyou.blue.bird.common.tool.LocalCache;
import java.io.File;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.CacheManager;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author 刘天佑
 * @date 2021-09-30
 */
@Configuration
@Slf4j
public class CacheConfig {

  @Bean
  public TimedCache<String, QrcodeLoginInfo> cache() {
    TimedCache<String, QrcodeLoginInfo> timedCache = CacheUtil.newTimedCache(60 * 1000);
    timedCache.setListener((key, cachedObject) -> {
      final File file = new File(cachedObject.getQrCodePath());
      if (file.exists()) {
        log.info("清除无用的登陆二维码：{}", cachedObject);
        file.delete();
      }
    });
    timedCache.schedulePrune(1000);
    return timedCache;
  }


  @Bean
  public CacheManager cacheManager() {
    return new ConcurrentMapCacheManager();
  }

  @Bean
  public LocalCache localCache() {
    return new LocalCache();
  }

}
